<template>
  <div>
    <h1>商品列表</h1>
    <div>
      <el-button type="primary" @click="onAddProd">添加商品</el-button>
      <el-button type="danger" @click="onHandleDeleteProd">批量删除</el-button>
    </div>
    <div style="margin-top: 10px">
      <el-form :inline="true" :model="searchData" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchData.prodName"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input
            v-model="searchData.prodId"
            placeholder="请输入商品ID"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadProdList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prodId" label="ID" />
      <el-table-column prop="prodSpu" label="SPU" />
      <el-table-column prop="prodName" label="名称" />
      <el-table-column prop="typeName" label="类型" />
      <el-table-column prop="brandName" label="品牌" />
      <el-table-column prop="unitName" label="单位" />
      <el-table-column prop="tagName" label="标签" />
      <el-table-column prop="apprName" label="供应商" />
      <el-table-column prop="prodImage" label="图片">
        <template #default="scope">
          <el-avatar
            v-if="scope.row.prodImage != null"
            :src="scope.row.prodImage"
          />
        </template>
      </el-table-column>
      <el-table-column prop="prodStatus" label="状态">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.prodStatus == 0">下架</el-tag>
          <el-tag type="primary" v-if="scope.row.prodStatus == 1">上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="kindName" label="种类" />
      <el-table-column prop="createTime" label="时间" />
      <el-table-column label="操作" width="250px">
        <template #default="scope">
          <el-button
            type="warning"
            size="small"
            @click="handleBuyProd(scope.row)"
          >
            购买
          </el-button>
          <el-button type="primary" size="small" @click="handleProd(scope.row)">
            商品
          </el-button>
          <el-button size="small" type="success" @click="handleAtta(scope.row)">
            商品附件
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div style="margin-top: 20px">
    <el-pagination
      v-model:current-page="searchData.pageNum"
      v-model:page-size="searchData.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="商品类型"
          :label-width="formLabelWidth"
          prop="kindId"
        >
          <el-radio-group v-model="form.kindId">
            <el-radio :value="0">实物商品</el-radio>
            <el-radio :value="1">虚拟商品</el-radio>
            <el-radio :value="2">卡密网盘</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品分类" :label-width="formLabelWidth">
          <el-tree-select
            v-model="form.typeId"
            :data="typeTree"
            check-strictly
            :render-after-expand="false"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="prodName"
        >
          <el-input v-model="form.prodName" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="商品SPU"
          :label-width="formLabelWidth"
          prop="prodSpu"
        >
          <el-input v-model="form.prodSpu" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品品牌" :label-width="formLabelWidth">
          <el-select v-model="form.brandId" placeholder="请选择品牌">
            <el-option
              v-for="item in brandListAll"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品单位" :label-width="formLabelWidth">
          <el-select v-model="form.unitId" placeholder="请选择单位">
            <el-option
              v-for="item in unitListAll"
              :key="item.unitId"
              :label="item.unitName"
              :value="item.unitId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品标签" :label-width="formLabelWidth">
          <el-select v-model="form.tagId" placeholder="请选择标签">
            <el-option
              v-for="item in tagListAll"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" :label-width="formLabelWidth">
          <el-select v-model="form.apprId" placeholder="请选择供应商">
            <el-option
              v-for="item in apprListAll"
              :key="item.apprId"
              :label="item.apprName"
              :value="item.apprId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="商品缩略图"
          :label-width="formLabelWidth"
          prop="prodImage"
        >
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/shop/type/uploadFile"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div>
    <el-dialog v-model="attaFormVisible" title="商品附件" width="800">
      <el-form :model="attaForm">
        <el-form-item label="商品轮播图" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="fileList"
            action="http://localhost:10010/shop/type/uploadFile"
            :headers="headers"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品视频" :label-width="formLabelWidth">
          <el-upload
            v-model:file-list="videoList"
            class="upload-demo"
            action="http://localhost:10010/shop/type/uploadFile"
            :headers="headers"
            :on-change="handleChange"
            :before-upload="beforeAvatarUpload"
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                作用于商品详情页顶部轮措的视频介绍，最大限制20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="上架时间" :label-width="formLabelWidth">
          <el-radio-group v-model="attaForm.upType">
            <el-radio :value="0">立即上架</el-radio>
            <el-radio :value="1">定时上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label=""
          :label-width="formLabelWidth"
          v-if="attaForm.upType == 1"
        >
          <el-date-picker
            v-model="attaForm.upTime"
            type="datetime"
            placeholder="请选择上架时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="定时下架" :label-width="formLabelWidth">
          <el-switch
            v-model="attaForm.downType"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item
          label=""
          :label-width="formLabelWidth"
          v-if="attaForm.downType == 1"
        >
          <el-date-picker
            v-model="attaForm.downTime"
            type="datetime"
            placeholder="请选择下架时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">放弃</el-button>
          <el-button type="primary" @click="onSubmitAddAtta"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getProdList,
  getTypeSelectTree,
  getBrandAll,
  getUnitAll,
  getTagAll,
  getApprAll,
  addProd,
  deleteAllProd,
  addProdAtta,
} from "@/api/api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, type UploadProps } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();

const ruleFormRef = ref<FormInstance>();
const imageUrl = ref("");
const headers = { token: sessionStorage.getItem("token") };
const tableData = ref([]);
const total = ref(0);
const searchData = ref({
  pageNum: 1,
  pageSize: 2,
  prodName: null,
  prodId: null,
});
const dialogFormVisible = ref(false);
const attaFormVisible = ref(false);
const formLabelWidth = "140px";
const typeTree = ref([]);
const brandListAll = ref([]);
const unitListAll = ref([]);
const tagListAll = ref([]);
const apprListAll = ref([]);

const form = ref({
  apprId: null,
  prodName: null,
  apprName: null,
  brandId: null,
  kindId: null,
  prodId: null,
  prodImage: null,
  prodSpu: null,
  prodStatus: null,
  tagId: null,
  typeId: null,
  unitId: null,
});
const attaForm = ref({
  attaId: 0,
  attaName: null,
  attaUrl: null,
  downTime: null,
  downType: null,
  imageList: [],
  prodId: 0,
  prodVideo: "",
  upTime: null,
  upType: null,
});
const rules = reactive<FormRules<any>>({
  prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  prodSpu: [{ required: true, message: "请输入商品spu", trigger: "blur" }],
  kindId: [{ required: true, message: "请选择商品类型", trigger: "change" }],
  prodImage: [
    { required: true, message: "请上传商品缩略图", trigger: "change" },
  ],
});
const restForm = () => {
  form.value = {
    apprId: null,
    prodName: null,
    apprName: null,
    brandId: null,
    kindId: null,
    prodId: null,
    prodImage: null,
    prodSpu: null,
    prodStatus: null,
    tagId: null,
    typeId: null,
    unitId: null,
  };
  imageUrl.value = "";
};
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log("handleSelectionChange", multipleSelection.value);
};

const onHandleDeleteProd = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择商品");
    return;
  }
  ElMessageBox.confirm("删除后数据无法恢复，您确认删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAllProd(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  imageUrl.value = response.data;
  form.value.prodImage = imageUrl.value;
};
//多图片上传
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
//上传视频
const videoList = ref<UploadUserFile[]>([]);
const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  videoList.value = videoList.value.slice(-3);
};
//上传文件之前，校验文件是否为视频文件
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log("beforeAvatarUpload", rawFile);
  if (rawFile.type !== "video/mp4") {
    ElMessage.error("上传的文件必须是视频格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传文件不能大于 2MB!");
    return false;
  }
  return true;
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchData.value.pageSize = val;
  loadProdList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchData.value.pageNum = val;
  loadProdList();
};
const onAddProd = () => {
  dialogFormVisible.value = true;
  restForm();
};
const onsubmitAddProd = () => {
  addProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("提交成功");
      dialogFormVisible.value = false;
      loadProdList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //提交表单
      onsubmitAddProd();
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};
const handleProd = (row: any) => {
  console.log("row", row);
};
const handleAtta = (row: any) => {
  console.log("row", row);
  attaForm.value.prodId = row.prodId;
  attaFormVisible.value = true;
};
const onSubmitAddAtta = () => {
  //轮播图
  attaForm.value.imageList = [];
  fileList.value.forEach((item: any) => {
    let img = {
      imageUrl: item.response.data,
    };
    attaForm.value.imageList.push(img);
  });
  //视
  if (videoList.value.length > 0) {
    console.log("onSubmitAddAtta", videoList.value);
    attaForm.value.prodVideo = videoList.value[0].response.data;
  }
  addProdAtta(attaForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加商品附件成功");
      attaFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
//购买
const handleBuyProd = (row: any) => {
  console.log("handleBuyProd", row);
  let prod = JSON.stringify(row);
  sessionStorage.setItem("buy", prod);
  router.push("/home/buy");
};
const loadProdList = () => {
  getProdList(searchData.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadProdList();
  getTypeSelectTree().then((res) => {
    if (res.data.code == 200) {
      typeTree.value = res.data.data;
    }
  });
  getBrandAll().then((res) => {
    if (res.data.code == 200) {
      brandListAll.value = res.data.data;
    }
  });
  getUnitAll().then((res) => {
    if (res.data.code == 200) {
      unitListAll.value = res.data.data;
    }
  });
  getTagAll().then((res) => {
    if (res.data.code == 200) {
      tagListAll.value = res.data.data;
    }
  });
  getApprAll().then((res) => {
    if (res.data.code == 200) {
      apprListAll.value = res.data.data;
    }
  });
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
